package com.songshuai.sales.tool.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.songshuai.sales.tool.constant.SalesToolConstant;
import com.songshuai.sales.tool.dto.request.label.AddLabelReqDto;
import com.songshuai.sales.tool.dto.request.label.UpdateLabelReqDto;
import com.songshuai.sales.tool.dto.response.label.QueryLabelDetailsResDto;
import com.songshuai.sales.tool.dto.response.label.QueryLabelsPageResDto;
import com.songshuai.sales.tool.dto.response.label.QueryLabelsResDto;
import com.songshuai.sales.tool.service.LabelRelationService;
import com.songshuai.sales.tool.service.LabelService;
import com.songshuai.sales.tool.service.LabelSopRelationService;
import com.songshuai.webapi.baseapi.constant.BaseConstant;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.model.sales.Label;
import com.songshuai.webapi.baseapi.model.sales.LabelSopRelation;
import com.songshuai.webapi.baseapi.pojo.BaseParmDto;
import com.songshuai.webapi.baseapi.pojo.QueryPageRes;
import com.songshuai.webapi.baseapi.pojo.QueryRes;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import com.songshuai.webapi.baseapi.utils.PropertiesUtil;
import com.songshuai.webapi.baseapi.utils.RequestParamValidUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 标签管理
 * @Author: lhx
 * @Date: 2019/3/11 17:45
 */
@Slf4j
@Api("标签管理")
@RestController
@RequestMapping("/api/label/")
public class LabelController {



    @Autowired
    private LabelService labelService;

    @Autowired
    private LabelSopRelationService labelSopRelationService;

    @Autowired
    private LabelRelationService labelRelationService;


    @ApiOperation(value = "根据标签名称查询标签集合")
    @PostMapping("queryLabelsPage")
    public QueryRes<List<QueryLabelsPageResDto>> queryLabels(@RequestBody BaseParmDto<String> request){
        try {
            Page<List<QueryLabelsPageResDto>> page = PageHelper.startPage(request.getPageIndex(), request.getPageSize());
            List<QueryLabelsPageResDto> labels = labelService.queryLabelsByName(request.getParam());
            return QueryPageRes.setQueryResData(labels, page.getTotal());
        } catch (Exception ex) {
            log.error("/api/label/queryLabelsPage", ex);
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED);
        }
    }


    @ApiOperation(value = "根据id查询标签详情")
    @GetMapping("queryLabelDetails")
    public QueryRes<QueryLabelDetailsResDto> queryLabelDetails(@RequestParam(value = "labelId")String labelId){
        try {
            Label label = labelService.selectByPrimaryKey(labelId);
            if (null != label) {
                QueryLabelDetailsResDto resDto = new QueryLabelDetailsResDto();
                PropertiesUtil.copyProperties(label, resDto);
                return QueryRes.setResData(resDto);
            }
            return new QueryRes<>();
        } catch (Exception ex) {
            log.error("/api/label/queryLabelDetails", ex);
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED);
        }
    }
    @ApiOperation(value = "新增标签")
    @PostMapping("addLabel")
    public QueryRes addLabel(@RequestBody @Valid AddLabelReqDto request, BindingResult result){
        if (result.hasErrors()){
            return new QueryRes(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorCode(), RequestParamValidUtil.getBindingResultMessage(result));
        }
        try {
            Label label = labelService.selectByEntity(new Label() {{
                setLabelName(request.getLabelName());
                setIsDelete(BaseConstant.IS_DELETE_FLAG_NO);
            }});
            if (null != label){
                return new QueryRes(ResultStatus.ERROR_CREATE_FAILED.getErrorCode(),"该标签名已存在");
            }

            if (labelService.insertLabel(request)){
                return new QueryRes();
            }
            return new QueryRes(ResultStatus.ERROR_CREATE_FAILED);
        } catch (Exception e) {
            log.error("/api/label/addLabel", e);
            throw new BusinessException(ResultStatus.ERROR_CREATE_FAILED);
        }
    }

    @ApiOperation(value = "修改标签")
    @PostMapping("updateLabel")
    public QueryRes updateLabel(@RequestBody @Valid UpdateLabelReqDto request, BindingResult result){
        if (result.hasErrors()){
            return new QueryRes(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorCode(), RequestParamValidUtil.getBindingResultMessage(result));
        }
        Label oldLabel = labelService.selectByPrimaryKey(request.getLabelId());
        if (oldLabel != null){
            if (null != oldLabel.getIsMoreChoose() && null != oldLabel.getIsShow()){
                //如需修改多选属性或显示状态，需要标签类型下所有子标签不与任何内容相关联。
                if (!oldLabel.getIsMoreChoose().equals(request.getIsMoreChoose())
                        || !oldLabel.getIsShow().equals(request.getIsShow())){
                    //管理文章数量
                    int i = labelService.queryRelationSopCount(request.getLabelId());
                    //TODO 关联人的数量
                    if (i>0 /*|| 关联人的数量大于0*/){
                        return new QueryRes(ResultStatus.ERROR_UPDATE_FAILED.getErrorCode(),"该标签类型下子标签有关联内容，无法修改");
                    }
                }
            }
        }else {
            return new QueryRes(ResultStatus.ERROR_INVALID_ARGUMENT);
        }
        Label label = labelService.selectByEntity(new Label() {{
            setLabelName(request.getLabelName());
            setIsDelete(BaseConstant.IS_DELETE_FLAG_NO);
        }});
        if (null != label && !label.getLabelId().equals(request.getLabelId())){
            return new QueryRes(ResultStatus.ERROR_CREATE_FAILED.getErrorCode(),"该标签名已存在");
        }
        if (labelService.updateLabel(request)){
            return new QueryRes();
        }
        return new QueryRes(ResultStatus.ERROR_UPDATE_FAILED);

    }

    @ApiOperation(value = "删除标签")
    @GetMapping("deleteLabel")
    public QueryRes deleteLabel(@RequestParam("labelId")String labelId){

        Label label = labelService.selectByPrimaryKey(labelId);
        //处理标签组
        if (SalesToolConstant.LABEL_PARENT_ID.equals(label.getParentId())){
            List<Label> labels = labelService.selectByEntityList(new Label() {{
                setIsDelete(BaseConstant.IS_DELETE_FLAG_NO);
                setParentId(label.getLabelId());
            }});
            //标签类型必须无子标签，且显示状态为不显示，才能删除
            if (!CollectionUtils.isEmpty(labels) || SalesToolConstant.LABEL_IS_SHOW_YES.equals(label.getIsShow())){
                return new QueryRes(ResultStatus.ERROR_DELETE_FAILED.getErrorCode(),"标签类型必须无子标签且显示状态为不显示才能删除");
            }

        }else {
            //处理子标签
            //子标签删除必须无任何内容与它相关联
            List<LabelSopRelation> labelSopRelations = labelSopRelationService.selectByEntityList(new LabelSopRelation() {{
                setLabelId(labelId);
            }});
            if (!CollectionUtils.isEmpty(labelSopRelations)){
                return new QueryRes(ResultStatus.ERROR_DELETE_FAILED.getErrorCode(),"该标签有关联文章，无法删除");
            }
            //TODO 查询是否关联人

        }

        if (labelService.deleteLabelById(labelId)){
            return new QueryRes();
        }
        return new QueryRes(ResultStatus.ERROR_DELETE_FAILED);

    }




    @ApiOperation(value = "查询标签集合")
    @GetMapping("queryLabels")
    public QueryRes<List<QueryLabelsResDto>> queryLabels(@RequestParam(value = "labelId",required = false)String labelId){
        try {
            return QueryRes.setResData(labelService.queryLabels(labelId));
        } catch (Exception e) {
            log.error("/api/label/queryLabels", e);
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED);
        }
    }





}
